<?php
namespace app\api\controller\dashboard;

use app\api\controller\Api;


class Notice extends Api {

    public function index() {
        $user = $this->request->user;

        $result = [];
        $where = [];
        $where[] = ['user_id', '=', $user['id']];
        $where[] = ['is_read', '=', 0];
        $noticeModel = new \app\common\system\model\Notice();
        // 根据type分组并统计数量
        $grouped = $noticeModel->where($where)->group('type')->column('count(*)', 'type');
        // type = 1 为新客资跟进通知
        $result['newCustomer'] = isset($grouped[1]) ? $grouped[1] : 0;
        // type = 2 为转单通知
        $result['transfer'] = isset($grouped[2]) ? $grouped[2] : 0;
        // type = 3 策划单通知
        $result['plan'] = isset($grouped[3]) ? $grouped[3] : 0;
        // type = 4 审核通知
        $result['audit'] = isset($grouped[4]) ? $grouped[4] : 0;

        return success($result);
    }

    // 根据type 读取通知列表
    public function read() {
        $user = $this->request->user;
        $post = $this->request->post();
        if (empty($post['type'])) {
            return error([], "参数错误");
        }

        $where = [];
        $where[] = ['user_id', '=', $user['id']];
        $where[] = ['type', '=', $post['type']];
        $where[] = ['is_read', '=', $post['status']];
        $noticeModel = new \app\common\system\model\Notice();
        $notices = $noticeModel->where($where)->order('id desc')->select();
        foreach ($notices as &$notice) {
            $notice->append(['from', 'user', 'title']);
        }

        return success($notices);
    }

    // 标记通知为已读
    public function hit() {
        $user = $this->request->user;
        $post = $this->request->post();
        if (empty($post['id'])) {
            return error([], "参数错误");
        }

        $where = [];
        $where[] = ['user_id', '=', $user['id']];
        $where[] = ['id', 'in', $post['id']];
        $noticeModel = new \app\common\system\model\Notice();
        $noticeModel->where($where)->update(['is_read' => 1]);

        return success([], "操作成功");
    }
}